package com.wing.order.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.response.ProductPackLabelVO;
import com.wing.order.dao.OrderReceiveLabelDao;
import com.wing.order.model.entity.*;
import com.wing.order.model.request.OrderReceiveLabelForm;
import com.wing.order.model.response.DistributionDemandDetailVO;
import com.wing.order.model.response.OrderReceiveLabelVO;
import com.wing.warehouse.model.response.PalletBoxListVO;
import com.wing.warehouse.service.PalletBoxListService;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 领货单明细-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class OrderReceiveLabelServiceImpl extends ServiceImpl<OrderReceiveLabelDao, OrderReceiveLabel> implements OrderReceiveLabelService {

    @Autowired
    private OrderReceiveService orderReceiveService;

    @Autowired
    private OrderReceiveDetailService orderReceiveDetailService;

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private DistributionDemandService distributionDemandService;

    @Autowired
    private DistributionDemandDetailService distributionDemandDetailService;

    @Autowired
    private EnterpriseClient enterpriseClient;

    @Autowired
    private PalletBoxListService boxListService;

    @Override
    public int add(OrderReceiveLabelForm orderReceiveLabelForm) {

        //校验

        OrderReceiveLabel orderReceiveLabel =new OrderReceiveLabel();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(OrderReceiveLabel.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(orderReceiveLabelForm, orderReceiveLabel, copyOptions);

        return baseMapper.insert(orderReceiveLabel);
    }

    @Override
    public List<OrderReceiveLabelVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<OrderReceiveLabelVO> pageList4app(Page page, Map<String, Object> params) {
        List<OrderReceiveLabelVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public OrderReceiveLabelVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional
    public void receiveSubmit(List<OrderReceiveLabel> list) {
        Long creator= JwtUtils.getLoginUserId();
        String creatorName=JwtUtils.getLoginUsername();
        OrderReceive orderReceive=new OrderReceive();
        String code=dynamicService.getDayNextCode("ord_order_receive");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String day=simpleDateFormat.format(new Date());
        orderReceive.setDay(Integer.valueOf(day));
        orderReceive.setNo(Integer.valueOf(code));
        orderReceive.setCode("RE-"+day+"-"+code);
        orderReceive.setTaskCode("TA-"+day+"-"+code);
        orderReceive.setLoadCode("LO-"+day+"-"+code);
        orderReceive.setDemandId(list.get(0).getDemandId());
        orderReceive.setCreator(creator);
        orderReceive.setCreatorName(creatorName);
        orderReceiveService.save(orderReceive);
        Long receiveId=orderReceive.getId();
        Map<String,Long> receiveDetailIdMap=new HashMap<>();
        for (OrderReceiveLabel orderReceiveLabel:list){

            List<OrderReceiveLabel> orderReceiveLabels=baseMapper.selectList(new QueryWrapper<OrderReceiveLabel>().eq("demand_id",orderReceiveLabel.getDemandId()).eq("pack_label_code",orderReceiveLabel.getPackLabelCode()));
            if (orderReceiveLabels.size()>0){
                throw new BusinessException("此包装条码已领货");
            }

            if (!receiveDetailIdMap.containsKey(orderReceiveLabel.getSkuCode())){
                OrderReceiveDetail orderReceiveDetail=new OrderReceiveDetail();
                orderReceiveDetail.setCreator(creator);
                orderReceiveDetail.setCreatorName(creatorName);
                orderReceiveDetail.setSkuCode(orderReceiveLabel.getSkuCode());
                orderReceiveDetail.setDemandId(orderReceiveLabel.getDemandId());
                orderReceiveDetail.setDemandDetailId(orderReceiveLabel.getDemandDetailId());
                orderReceiveDetail.setQuantity(orderReceiveLabel.getQuantity().intValue());
                orderReceiveDetail.setReceiveId(receiveId);
//                List<OrderReceiveDetail> orderReceiveDetails=orderReceiveDetailService.list(new QueryWrapper<OrderReceiveDetail>().eq("demand_id",orderReceiveLabel.getDemandId()).eq("sku_code",orderReceiveLabel.getSkuCode()));
//                if (orderReceiveDetails.size()==0){
                    orderReceiveDetailService.save(orderReceiveDetail);
                    receiveDetailIdMap.put(orderReceiveLabel.getSkuCode(),orderReceiveDetail.getId());
//                }else{
//                    receiveDetailIdMap.put(orderReceiveLabel.getSkuCode(),orderReceiveDetails.get(0).getId());
//                }
            }

            JsonResult<ProductPackLabelVO> jsonResult=enterpriseClient.getProductPackLabelVOList(orderReceiveLabel.getPackLabelCode(),0);
            ProductPackLabelVO labels=jsonResult.getData();
            if (labels==null){
                throw new BusinessException("未找到包装条码");
            }
            if (labels.getSurplusQuantity().intValue()<orderReceiveLabel.getQuantity().intValue()){
                throw new BusinessException("领取数量不能大于包装条码对应的数量");
            }

//            enterpriseClient.updateProductPackLabe(orderReceiveLabel.getPackLabelId(),orderReceiveLabel.getQuantity().intValue());

            enterpriseClient.extractPackLabel(orderReceiveLabel.getPackLabelCode(),orderReceiveLabel.getQuantity().intValue(),1);

            DistributionDemandDetailVO distributionDemandDetail=distributionDemandDetailService.get4appById(orderReceiveLabel.getDemandDetailId());
            if (distributionDemandDetail==null){
                throw new BusinessException("未找到配货需求单明细数据");
            }
            Integer quantitySurplus=distributionDemandDetail.getQuantityConfirm().intValue();
            if (distributionDemandDetail.getQuantityReceive()!=null){
                quantitySurplus=quantitySurplus-distributionDemandDetail.getQuantityReceive();
            }
            quantitySurplus=quantitySurplus-orderReceiveLabel.getQuantity().intValue();
            if (quantitySurplus<0){
                throw new BusinessException("领货数不能大于配货需求确认数");
            }

            if (quantitySurplus==0){
                DistributionDemandDetail distributionDemandDetail4Update=new DistributionDemandDetail();
                distributionDemandDetail4Update.setId(distributionDemandDetail.getId());
                distributionDemandDetail4Update.setStatus(DistributionDemandDetail.Status.finish);
                distributionDemandDetailService.updateById(distributionDemandDetail4Update);
            }

            PalletBoxListVO palletBoxListVO=boxListService.getPalletBoxByLabelCode(orderReceiveLabel.getPackLabelCode());
            if (palletBoxListVO!=null){
                orderReceiveLabel.setWarehouseId(palletBoxListVO.getWarehouseId());
                orderReceiveLabel.setAreaId(palletBoxListVO.getAreaId());
                orderReceiveLabel.setShelfId(palletBoxListVO.getShelfId());
                orderReceiveLabel.setSpaceId(palletBoxListVO.getSpaceId());
            }

            orderReceiveLabel.setReceiveId(receiveId);
            orderReceiveLabel.setReceiveDetailId(receiveDetailIdMap.get(orderReceiveLabel.getSkuCode()));
            orderReceiveLabel.setCreator(creator);
            orderReceiveLabel.setCreatorName(creatorName);
            baseMapper.insert(orderReceiveLabel);
        }

        int count=distributionDemandDetailService.countNotFinish(list.get(0).getDemandId());
        if (count==0){
            DistributionDemand distributionDemand=new DistributionDemand();
            distributionDemand.setId(list.get(0).getDemandId());
            distributionDemand.setStatus(DistributionDemand.Status.finish);
            distributionDemandService.updateById(distributionDemand);
        }
    }
}
